<template>
  <div class="ad-manage">
    <!-- 操作栏 -->
    <div class="actions">
      <el-button type="primary" @click="openDialog">新增广告</el-button>
    </div>

    <!-- 表格 -->
    <div class="table-wrapper">
      <el-table :data="adList" border style="width: 100%" row-key="id">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="title" label="标题" min-width="160" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.image"
              style="width: 80px; height: 60px"
              fit="cover"
              @click="previewRowImage(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            {{ getTypeLabel(row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="广告位" width="140">
          <template #default="{ row }">
            {{ getPositionLabel(row.position) }}
          </template>
        </el-table-column>
        <el-table-column prop="link" label="链接地址" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
              {{ row.status === 'enabled' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editAd(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑广告' : '新增广告'"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="类型" required>
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 200px">
            <el-option label="平台广告" value="platform" />
            <el-option label="招商广告" value="business" />
          </el-select>
        </el-form-item>

        <el-form-item label="广告位" required>
          <el-select v-model="form.position" placeholder="请选择广告位" style="width: 200px">
            <el-option label="轮播图" value="carousel" />
            <el-option
              v-for="pos in fixedPositions"
              :key="pos"
              :label="getPositionLabel(pos)"
              :value="pos"
              :disabled="isPositionOccupied(pos, form.id)"
            />
          </el-select>
          <span class="text-gray text-xs ml-2">轮播图可多个，固定广告位唯一</span>
        </el-form-item>

        <el-form-item label="标题" required>
          <el-input v-model="form.title" placeholder="请输入广告标题" />
        </el-form-item>

        <el-form-item label="上传图片" required>
          <el-upload
            class="upload-demo"
            action=""
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleUploadChange"
            :file-list="uploadFileList"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div v-if="uploadFileList.length" class="hint">已选择图片：点缩略图可放大预览</div>
        </el-form-item>

        <el-form-item label="链接地址">
          <el-input v-model="form.link" placeholder="请输入跳转链接" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="[previewImage]"
      :initial-index="0"
      @close="previewVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { getAds, addAd, updateAd, deleteAd, type Ad, type AdType, type AdPosition } from '@/api/ad'

/* -------------------- Label 映射 -------------------- */
const TYPE_LABELS: Record<AdType, string> = {
  platform: '平台广告',
  business: '招商广告'
}
const POSITION_LABELS: Record<AdPosition, string> = {
  carousel: '轮播图',
  fixed1: '固定广告位1',
  fixed2: '固定广告位2',
  fixed3: '固定广告位3',
  fixed4: '固定广告位4',
  fixed5: '固定广告位5'
}

function getTypeLabel(t: AdType) {
  return TYPE_LABELS[t] ?? ''
}
function getPositionLabel(p: AdPosition) {
  return POSITION_LABELS[p] ?? ''
}

/* -------------------- 数据 -------------------- */
const adList = ref<Ad[]>([])
const dialogVisible = ref(false)
const previewVisible = ref(false)
const previewImage = ref('')
const uploadFileList = ref<UploadFile[]>([])
const fixedPositions: AdPosition[] = ['fixed1', 'fixed2', 'fixed3', 'fixed4', 'fixed5']

const form = ref<Partial<Ad>>({
  type: 'platform',
  position: 'carousel',
  title: '',
  image: '',
  link: '',
  status: 'enabled'
})

/* -------------------- 生命周期 -------------------- */
onMounted(async () => {
  await loadAds()
})

async function loadAds() {
  const res = (await getAds()) as Ad[] | { data: Ad[] }
  adList.value = Array.isArray(res) ? res : (res.data ?? [])
}

/* -------------------- 方法 -------------------- */
function handlePreview(file: UploadFile) {
  previewImage.value = file.url || (file.raw ? URL.createObjectURL(file.raw) : '')
  previewVisible.value = true
}
function previewRowImage(row: Ad) {
  previewImage.value = row.image
  previewVisible.value = true
}
function openDialog() {
  resetForm()
  dialogVisible.value = true
}
function resetForm() {
  form.value = {
    id: undefined,
    type: 'platform',
    position: 'carousel',
    title: '',
    image: '',
    link: '',
    status: 'enabled'
  }
  uploadFileList.value = []
}
function editAd(row: Ad) {
  form.value = { ...row }
  uploadFileList.value = row.image ? [{ name: '已上传图片', url: row.image } as UploadFile] : []
  dialogVisible.value = true
}

/* 删除 */
async function handleDelete(id: number) {
  try {
    await deleteAd(id)
    ElMessage.success('删除成功')
    await loadAds()
  } catch (err) {
    console.error(err)
    ElMessage.error('删除失败')
  }
}

/* 保存 */
async function handleSave() {
  if (!form.value.title) return ElMessage.error('请输入广告标题')
  if (!form.value.image) return ElMessage.error('请上传图片')

  try {
    if (form.value.id) {
      const updated = await updateAd(form.value.id, form.value)
      const idx = adList.value.findIndex(ad => ad.id === updated.id)
      if (idx !== -1) adList.value[idx] = updated
      ElMessage.success('更新成功')
    } else {
      const created = await addAd(form.value as Omit<Ad, 'id' | 'createdAt'>)
      adList.value.push(created)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false

    // 🔥 重新拉一次最新列表（含排序、分页等）
    await loadAds()
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

/* 位置唯一校验 */
function isPositionOccupied(pos: AdPosition, editingId?: number) {
  return adList.value.some(ad => ad.position === pos && ad.id !== editingId && pos !== 'carousel')
}

/* 上传图片 */
function handleUploadChange(file: UploadFile) {
  if (!file.raw) return
  const reader = new FileReader()
  reader.onload = e => {
    form.value.image = e.target?.result as string
    uploadFileList.value = [{ name: file.name ?? 'image', url: form.value.image } as UploadFile]
  }
  reader.readAsDataURL(file.raw)
}
function handleRemove() {
  form.value.image = ''
  uploadFileList.value = []
}
</script>

<style>
.table-wrapper {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  overflow-x: auto; /* 保持表格横向滚动可用 */
}
.actions {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}
.ad-manage {
  padding: 16px;
}
</style>
